<?php

namespace Admin\Model;
use Admin\Model\BaseModel;
class AdminGroupModel extends BaseModel
{
    public $tableName = 'admin_group';
    public $_validate = array(
        array('name', '', '组名已存在', 0, 'unique', 3),
    );

    public function getUserGroupInfo($id)
    {
        $groupInfo = $this->where(array('id' => $id))->find();
        if (false === $groupInfo) {
            return array();
        }
        return $groupInfo;
    }

    /**
     * 用户组分页列表
     *
     */
    public function getNewsPageList($where, $order = '', $nowPage = 1, $pageSize = 10)
    {
        $count = $this->where($where)->count();
        $Page = new \Admin\Util\Page($count, $pageSize);
        $searchPage = $Page->totalPages > $nowPage ? $nowPage : $Page->totalPages;
        $data['list'] = $this->where($where)->order($order)->page($searchPage . ',' . $Page->listRows)->select();
        $data['page'] = $Page->show();
        return $data;
    }

    /**
     * 得到所有用户组列表
     * @param type $where
     * @return type
     */
    public function getGroupAllList()
    {
        $groupList = $this->select();
        if (false === $groupList) {
            return array();
        }
        return $groupList;
    }

    /**
     * 保存数据
     * @param type $dataArray
     * @return type
     * @throws Exception
     */
    public function doSave($dataArray)
    {
        if (empty($dataArray['id'])) {
            $dataArray['create_time'] = date("Y-m-d H:i:s");
        }
        $dataArray['update_time'] = date("Y-m-d H:i:s");

        if (false === $this->create($dataArray)) {
            throw new \Exception($this->getError());
        }

        if (empty($dataArray['id'])) {
            $res = $this->add($dataArray);
        } else {
            $res = $this->save($dataArray);
        }
        return $res;
    }

    /**
     * 删除信息
     * @param type $id
     * @return type
     */
    public function delGroup($id)
    {
        //故意查询一下，如果没有info缓存,_after_del方法会执行不正常
        $groupInfo = $this->getUserGroupInfo($id);
        if (empty($groupInfo)) {
            return TRUE;
        }
        $where['id'] = $id;
        $res = $this->where($where)->delete();
        return $res;
    }

    /**
     * 通过id查名字
     * @param type $id
     * @return type
     */
    public function getGroupName4Id($id)
    {
        $groupInfo = $this->getUserGroupInfo($id);
        return $groupInfo['name'];
    }

    protected function _after_update($data, $options)
    {

    }

    protected function _after_delete($data, $options)
    {

    }

    protected function _after_insert($data, $options)
    {

    }


}
